#!/usr/bin/env python

# convertmp4tompeg.py - Convert mp4 to mpeg
# Based on makevid.py by Sam Peterson
# (c) Emlyn O'Regan 2009

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

"""
convertmp4tompeg.py by Emlyn O'Regan <emlynoregan@gmail.com>

Requirements: mencoder

This script converts an mp4 video to mpeg. It takes one argument, and an optional second argument. The first is the name of the mp4, the second is the name of the output mpeg (optional).

Example:

convertmp4tompeg.py something.mp4  # this will output to output.mpeg
convertmp4tompeg.py something.mp4 other.mpeg
"""

import os, sys

fps = 30

arglen = len(sys.argv)
if arglen < 3 or arglen > 5:
    print "Usage: split4youtube.py mp4file numpieces [mpegout [offsetsecs]]"
    sys.exit(1)

needexit = False

if not os.path.exists(sys.argv[1]):
    print "%s doesn't exist" % sys.argv[1]
    needexit = True

if arglen == 4 and os.path.exists(sys.argv[3]):
    print "%s already exists" % sys.argv[3]
    needexit = True

if needexit: sys.exit(1);

outputpath = "output.mpg"
if arglen >= 4:
    outputpath = sys.argv[3]

offsetsec = 0
if arglen >= 5:
    offsetsec = int(sys.argv[4])

numpieces = int(sys.argv[2])
for i in range(1, numpieces+1):
    startmins = (i-1) * 15
    starthrs = 0
    startsecs = offsetsec
    while startsecs >= 60:
        startsecs=startsecs-60
        startmins=startmins+1
    while startmins >= 60:
        startmins=startmins-60
        starthrs=starthrs+1

    if "%s" in outputpath:
        outputpathi = (outputpath % (i))
    else:
        outputpathi = ("%s%s.avi") % (outputpath, i)
	
    mencoder_cmd = ('mencoder "%s" -ss %s:%s:%s -endpos 00:15:00 -ovc xvid -xvidencopts bitrate=4400 -oac mp3lame -o "%s"') \
    % (sys.argv[1], starthrs, startmins, startsecs, outputpathi)
#    % (sys.argv[1], starthrs, startmins, endhrs, endmins, outputpathi)


    print "Starting mencoder"
    print mencoder_cmd
    if os.system(mencoder_cmd) == 0:
    	print ("Conversion is complete, output written to %s") % (outputpathi)
    else:
        print ("Conversion failed, halting")
	sys.exit(1)

